import jieba
from wordcloud import WordCloud
from imread import imread
import matplotlib.pyplot as plt

fr = open('writing.txt', 'r', encoding='utf-8')

s = ""
data = {}

for line in fr:
    line = line.strip()
    for x in range(0, len(line)):
        if line[x] in [' ', '\t', '\n', '。', '，', '[', ']', '（', '）', ':', '-',
                       '？', '！', '《', '》', '、', '；', '“', '”', '……', '0', '1', '2', '3', '4', '5',
                       '6', '7', '8', '9', '=', '~', '…', '一', '二', '三', '四', '五', '六', '七', '八', '九', '十']:
            continue
        s += str(line[x])

seg_list = jieba.cut(s, cut_all=False, HMM=True)
for word in seg_list:
    if len(word) >= 2:
        if not data.__contains__(word):
            data[word] = 0
        data[word] += 1
# data=sorted(data.items(),key=lambda d:d[1],reverse=True)
# print(data)

my_wordcloud = WordCloud(
    background_color='white',  # 设置背景颜色
    max_words=400,  # 设置最大实现的字数
    font_path=r'SimHei.ttf',  # 设置字体格式，如不设置显示不了中文
    mask=imread('map.jpg'),
    width=1000,
    height=1000,
).generate_from_frequencies(data)
plt.figure()
plt.imshow(my_wordcloud)
plt.axis('off')
plt.show()  # 展示词云
my_wordcloud.to_file('result.jpg')
fr.close()
